#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
码将游戏打包环境自动设置脚本
自动检查和安装必要的依赖，配置打包环境
"""

import os
import sys
import subprocess
import platform
from pathlib import Path

class BuildEnvSetup:
    def __init__(self):
        self.system = platform.system()
        self.python_version = sys.version_info
        self.project_root = Path(__file__).parent
        
    def print_header(self):
        print("=" * 50)
        print("🎮 码将游戏打包环境设置工具")
        print("=" * 50)
        print(f"操作系统: {self.system}")
        print(f"Python版本: {self.python_version.major}.{self.python_version.minor}.{self.python_version.micro}")
        print(f"项目路径: {self.project_root}")
        print()
        
    def check_python_version(self):
        """检查Python版本"""
        print("🔍 检查Python版本...")
        if self.python_version.major != 3 or self.python_version.minor < 7:
            print("❌ 错误：需要Python 3.7或更高版本")
            return False
        print("✅ Python版本检查通过")
        return True
        
    def install_dependencies(self):
        """安装依赖包"""
        print("\n📦 安装项目依赖...")
        
        try:
            # 升级pip
            subprocess.check_call([sys.executable, "-m", "pip", "install", "--upgrade", "pip"])
            
            # 安装依赖
            if (self.project_root / "requirements.txt").exists():
                subprocess.check_call([sys.executable, "-m", "pip", "install", "-r", "requirements.txt"])
                print("✅ 项目依赖安装完成")
            else:
                # 手动安装核心依赖
                dependencies = ["pygame>=2.0.0", "pyinstaller>=5.0.0"]
                for dep in dependencies:
                    subprocess.check_call([sys.executable, "-m", "pip", "install", dep])
                print("✅ 核心依赖安装完成")
                
        except subprocess.CalledProcessError as e:
            print(f"❌ 依赖安装失败: {e}")
            return False
            
        return True
        
    def check_game_files(self):
        """检查游戏文件完整性"""
        print("\n📁 检查游戏文件...")
        
        required_files = [
            "game.py",
            "tile.py", 
            "gui.py",
            "player.py",
            "crypto_rules.py",
            "规则.txt"
        ]
        
        required_dirs = [
            "res",
            "麻将图片",
            "密码学者"
        ]
        
        missing_files = []
        for file in required_files:
            if not (self.project_root / file).exists():
                missing_files.append(file)
                
        missing_dirs = []
        for dir_name in required_dirs:
            if not (self.project_root / dir_name).exists():
                missing_dirs.append(dir_name)
                
        if missing_files or missing_dirs:
            print("❌ 缺少必要文件:")
            for file in missing_files:
                print(f"   - {file}")
            for dir_name in missing_dirs:
                print(f"   - {dir_name}/")
            return False
            
        print("✅ 游戏文件检查完成")
        return True
        
    def test_game_import(self):
        """测试游戏模块导入"""
        print("\n🧪 测试游戏模块...")
        
        try:
            import pygame
            print(f"✅ Pygame {pygame.version.ver} 导入成功")
            
            # 测试主要模块
            sys.path.insert(0, str(self.project_root))
            import tile
            import gui
            import player
            import crypto_rules
            print("✅ 游戏模块导入测试通过")
            
        except ImportError as e:
            print(f"❌ 模块导入失败: {e}")
            return False
            
        return True
        
    def create_build_scripts(self):
        """确保构建脚本存在且可执行"""
        print("\n📝 检查构建脚本...")
        
        scripts = ["build.bat", "build.sh", "build_config.spec"]
        
        for script in scripts:
            script_path = self.project_root / script
            if script_path.exists():
                print(f"✅ {script} 已存在")
                
                # 给Shell脚本执行权限
                if script.endswith('.sh') and self.system != 'Windows':
                    os.chmod(script_path, 0o755)
                    
            else:
                print(f"⚠️ {script} 不存在，请查看封装指南")
                
    def show_next_steps(self):
        """显示下一步操作指南"""
        print("\n" + "=" * 50)
        print("🚀 环境设置完成！下一步操作：")
        print("=" * 50)
        
        if self.system == "Windows":
            print("Windows用户：")
            print("1. 双击运行 build.bat")
            print("2. 或在命令行执行：pyinstaller build_config.spec")
        else:
            print("Linux/Mac用户：")
            print("1. 执行：chmod +x build.sh && ./build.sh")
            print("2. 或在命令行执行：pyinstaller build_config.spec")
            
        print("\n打包输出：")
        print("- 多文件版本：dist/码将-密码学麻将/")
        print("- 单文件版本：pyinstaller build_onefile.spec")
        
        print("\n制作安装包（Windows）：")
        print("1. 安装 Inno Setup")
        print("2. 编译 installer_config.iss")
        
        print("\n📚 更多信息请查看：封装指南.md")
        
    def run(self):
        """运行完整的环境设置流程"""
        self.print_header()
        
        if not self.check_python_version():
            return False
            
        if not self.install_dependencies():
            return False
            
        if not self.check_game_files():
            return False
            
        if not self.test_game_import():
            return False
            
        self.create_build_scripts()
        self.show_next_steps()
        
        return True

def main():
    """主函数"""
    setup = BuildEnvSetup()
    
    try:
        success = setup.run()
        if success:
            print("\n🎉 环境设置成功！现在可以开始打包了。")
        else:
            print("\n❌ 环境设置失败，请检查上述错误信息。")
            sys.exit(1)
            
    except KeyboardInterrupt:
        print("\n\n用户取消操作。")
        sys.exit(0)
    except Exception as e:
        print(f"\n❌ 未知错误: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main() 